package com.mzy.linear_struct.hot100.链表;

/**
 * @Author: mizy3
 * @Date: 2024/07/31/下午5:42
 * @Description:
 */
public class Pro2两数相加 {

   /* public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode();
        int carry = 0;
        ListNode cur = ans;
        while (l1 != null || l2 != null) {
            int x = l1 != null ? l1.val : 0;
            int y = l2 != null ? l2.val : 0;
            int sum = x + y + carry;
            carry = sum / 10;
            int num = sum % 10;

            cur.next = new ListNode(num);
            cur = cur.next;
            if(l1 != null) {
                l1 = l1.next;
            }
            if(l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            cur.next = new ListNode(1);
        }

        return ans.next;
    }*/


    public static void main(String[] args) {
        ListNode listNode = new ListNode(2, new ListNode(4, new ListNode(3, new ListNode(8))));
        ListNode listNode1 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode x = new Pro2两数相加().addTwoNumbers(listNode, listNode1);
        while (x != null) {
            System.out.print(x.val);
            x = x.next;
        }
    }

    private ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode ans = dummy;
        boolean carry = false;
        while (l1 != null || l2 != null) {
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            int sum = a + b + (carry ? 1 : 0);
            carry = sum >= 10;
            sum = sum % 10;

            dummy.next = new ListNode(sum);
            dummy = dummy.next;
            if(l1 != null) {
                l1 = l1.next;
            }

            if(l2 != null) {
                l2 = l2.next;
            }
        }
        if(carry) {
            dummy.next = new ListNode(1);
        }
        return ans.next;
    }
}
